package com.dkd.job;

import cn.elegent.lock.annotation.ELegentLock;
import com.dkd.config.constant.SystemKeys;
import com.dkd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author DiXiaoNie
 * @since 2023/2/2 10:22
 * 定时任务工单初始化
 */
@Component
@Slf4j
public class WorkInitJob {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0 0 * * ?")
    @ELegentLock(lockName = "dkd-work")
    public void workCountInit() {
        log.info("定时任务开始");

        this.userService.list().forEach(user -> {
            //不考虑给管理员投放工单
            if (!"1001".equals(user.getRoleCode())) {
                //key的规则 固定字符串+当前日期+区域+工单类别
                String key = SystemKeys.REGION_TASK_KEY_PREF
                        + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                        + "." + user.getRegionId()
                        + "." + user.getRoleCode();
                //保存到redis中
                this.redisTemplate.opsForZSet().add(key, user.getId(), 0);
                //过期时间一天
                this.redisTemplate.expire(key, Duration.ofDays(1));
            }
        });
    }
}
